﻿using XW.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using NPOI.SS.Formula.Functions;
namespace XW.Utils
{
    public static class SXHttpContext
    {
        private static ILog L = LogProvider.GetCurrentClassLogger();
        public static IApplicationBuilder app;
        static SXHttpContext()
        { }

        /// <summary>
        /// 获取当前上下文
        /// </summary>
        public static HttpContext Current
        {
            get
            {
                if (app == null) { 
                    return null;
                }
                object factory = app.ApplicationServices.GetService(typeof(IHttpContextAccessor));

                HttpContext context = ((IHttpContextAccessor)factory).HttpContext;
                return context;
            }
        }

        /// <summary>
        /// 获取服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T? GetService<T>() where T : class
        {
            return GetServiceProvider().GetService<T>();
            //if (  != null)
            //{
             
            //}
            //if (app.ApplicationServices == null)
            //{
            //    return default(T);
            //}
            //else
            //{
            //    return app.ApplicationServices.GetService(typeof(T)) as T;
            //}
        }

        public static IServiceProvider GetServiceProvider() {
            if (Current != null && Current.RequestServices != null)
            {
                return Current.RequestServices;
            }
            return app.ApplicationServices;
        }
        public static string GetUserIp()
        {
            if (Current != null)
            {
                return Current.GetUserIp();
            }
            else
            {
                return "";
            }
          
        }
        public static string GetUserIp(this HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            if (ip.IsNotNullAndEmpty())
            {
                // 解决代理的情况下获取实际IP
                ip = ip.Split(',')[0].SafeTrim();
            }
            // L.Debug("当前用户IP:{ip}",ip);
            return ip;
        }
    }
}
